package com.tl.app.service.impl;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tl.app.domain.AppOrder;
import com.tl.app.mapper.AppOrderMapper;
import com.tl.app.service.IAppOrderService;
import com.tl.common.constant.Constants;
import com.tl.common.core.domain.entity.SysUser;
import com.tl.common.core.redis.RedisCache;
import com.tl.common.exception.CustomException;
import com.tl.common.exception.UtilException;
import com.tl.common.utils.CodeUtil;
import com.tl.common.utils.DateUtils;
import com.tl.common.utils.IPUtil;
import com.tl.system.service.ISysConfigService;
import com.tl.system.service.ISysUserService;
import com.tl.wechat.pay.domain.WxPayInfo;
import com.tl.wechat.pay.service.WeChatPayService;

/**
 * 订单Service业务层处理
 * 
 * @author suhp
 * @date 2024-07-07
 */
@Service
public class AppOrderServiceImpl implements IAppOrderService 
{
    @Autowired
    private AppOrderMapper appOrderMapper;
    
    @Autowired
    private ISysConfigService configService;
    
    @Autowired
    private WeChatPayService weChatPayService;
    
    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private RedisCache redisCache;
    
    /**
     * 过期时间
     */
    private Integer expireTime = 5;
    
    
    /**
     * 查询订单
     * 
     * @param orderId 订单主键
     * @return 订单
     */
    @Override
    public AppOrder selectAppOrderByOrderId(Long orderId)
    {
        return appOrderMapper.selectAppOrderByOrderId(orderId);
    }

    /**
     * 查询订单列表
     * 
     * @param appOrder 订单
     * @return 订单
     */
    @Override
    public List<AppOrder> selectAppOrderList(AppOrder appOrder)
    {
        return appOrderMapper.selectAppOrderList(appOrder);
    }

    /**
     * 新增订单
     * 
     * @param appOrder 订单
     * @return 结果
     */
    @Override
    @Transactional
    public synchronized AppOrder insertAppOrder(AppOrder appOrder){
    	String configValue=configService.selectConfigByKey("app.platform.cy");
    	double cyBfb=convertPercentageToNumber(configValue);
    	BigDecimal price=new BigDecimal(appOrder.getPrice());
    	BigDecimal cyPrice=new BigDecimal(cyBfb);
    	BigDecimal platformPrice=price.multiply(cyPrice).setScale(0, BigDecimal.ROUND_HALF_UP);
    	BigDecimal servicePrice = price.subtract(platformPrice).setScale(0, BigDecimal.ROUND_HALF_UP);
    	//平台金额
    	appOrder.setPlatformPrice(platformPrice.toString());
    	//服务金额
    	appOrder.setServicePrice(servicePrice.toString());
    	appOrder.setOrderNo(CodeUtil.getOrderCode(appOrder.getType().toUpperCase()));
        appOrder.setCreateTime(DateUtils.getNowDate());
        appOrderMapper.insertAppOrder(appOrder);
        return appOrder;
    }
    
    
    /**
     * 发起支付订单
     * 
     * @param appOrder 订单
     * @return 结果
     */
    @Override
    public synchronized Map<String, Object> payOrder(HttpServletRequest req,AppOrder appOrder){
    	SysUser su=userService.selectUserById(appOrder.getXdUserId());
    	if(su==null||StringUtils.isEmpty(su.getOpenId())) {
    		 throw new CustomException("未找到下单用户相关信息");
    	}
    	System.out.println("《《《===订单支付：订单信息组装===》》》");
    	String configValue=configService.selectConfigByKey("app.platform.cy");
    	double cyBfb=convertPercentageToNumber(configValue);
    	BigDecimal price=new BigDecimal(appOrder.getPrice());
    	BigDecimal cyPrice=new BigDecimal(cyBfb);
    	BigDecimal platformPrice=price.multiply(cyPrice).setScale(0, BigDecimal.ROUND_HALF_UP);
    	BigDecimal servicePrice = price.subtract(platformPrice).setScale(0, BigDecimal.ROUND_HALF_UP);
    	//平台金额
    	appOrder.setPlatformPrice(platformPrice.toString());
    	//服务金额
    	appOrder.setServicePrice(servicePrice.toString());
    	//创建订单编号
    	String orderCode=CodeUtil.getOrderCode(appOrder.getType().toUpperCase());
    	appOrder.setOrderNo(orderCode);
        appOrder.setCreateTime(DateUtils.getNowDate());
    	Integer sjPrice=Integer.valueOf(price.multiply(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toString());
    	String serviceInfo=appOrder.getServiceInfo();
    	System.out.println("《《《===订单支付：订单信息组装完成，发起支付请求===》》》");
    	WxPayInfo wpi=new WxPayInfo();
    	wpi.setOpenId(su.getOpenId());
    	wpi.setOutTradeNo(orderCode);
    	wpi.setTotalFee(sjPrice);
    	wpi.setBody(serviceInfo);
    	String ip=IPUtil.getClientIP(req);
    	wpi.setCliIp(ip);
    	Map<String, Object> wxMap=weChatPayService.createWXOrder(wpi);
    	redisCache.setCacheObject(Constants.PAY_WX_PREFIX+orderCode,appOrder,expireTime,TimeUnit.MINUTES);
    	System.out.println("《《《===订单支付：订单信息支付请求完成===》》》");
        return wxMap;
    }
    

    /**
     * 修改订单
     * 
     * @param appOrder 订单
     * @return 结果
     */
    @Override
    public int updateAppOrder(AppOrder appOrder)
    {
        return appOrderMapper.updateAppOrder(appOrder);
    }

    /**
     * 批量删除订单
     * 
     * @param orderIds 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteAppOrderByOrderIds(Long[] orderIds)
    {
        return appOrderMapper.deleteAppOrderByOrderIds(orderIds);
    }

    /**
     * 删除订单信息
     * 
     * @param orderId 订单主键
     * @return 结果
     */
    @Override
    public int deleteAppOrderByOrderId(Long orderId)
    {
        return appOrderMapper.deleteAppOrderByOrderId(orderId);
    }
    
    public static void main(String[] args) {
		System.out.println(convertPercentageToNumber("20"));
	}
    
    /**
     * 
     * @param percentage
     * @return
     */
    public static double convertPercentageToNumber(String percentage) {
        NumberFormat formatter = NumberFormat.getNumberInstance();
        try {
            Number number = formatter.parse(percentage.substring(0, percentage.length() - 1));
            return number.doubleValue() / 10;
        } catch (ParseException e) {
        	 throw new UtilException("平台订单抽佣金额设置有误");
        }
    }

	@Override
	public List<Map<String, Object>> selecRandomOrderList(AppOrder appOrder) {
		return appOrderMapper.selecRandomOrderList(appOrder);
	}
	
	@Override
	public String selectAppOrderWeekClerkPrice(Long fwUserId) {
		return appOrderMapper.selectAppOrderWeekClerkPrice(fwUserId);
	}

	@Override
	public List<Map<String, Object>> selectAppOrderRnak(String type) {
		return appOrderMapper.selectAppOrderRnak(type);
	}
}
